import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 自己写导入组件的代码
// import login from '@/views/login'
// import layout from '@/layout'
// import home from '@/views/home'
// import ask from '@/views/ask'
// import video from '@/views/video'
// import mine from '@/views/mine'
// import edit from '@/views/mine/edit'
// import article from '@/views/article'
// import chat from '@/views/mine/chat'
// import search from '@/views/search'

// 路由懒加载的方式
const login = () => import('@/views/login')
const layout = () => import('@/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const video = () => import('@/views/video')
const mine = () => import('@/views/mine')
const edit = () => import('@/views/mine/edit')
const article = () => import('@/views/article')
const chat = () => import('@/views/mine/chat')
const search = () => import('@/views/search')

const routes = [
  { path: '', redirect: '/layout/home' },
  { name: 'login', path: '/login', component: login },
  { name: 'edit', path: '/mine/edit', component: edit, meta: { needLogin: true } },
  { name: 'chat', path: '/mine/chat', component: chat, meta: { needLogin: true } },
  { name: 'search', path: '/search', component: search },
  // 名字不能跟原生标签冲突(原生里有acticle这个标签的)
  { name: 'articleDetail', path: '/article', component: article },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      // 子路由可以不加/，代表先拼接父路由路径再访问
      { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        meta: {
          needLogin: true
        }
      },
    ]
  },
]
// 路由对象
const router = new VueRouter({
  routes
})


// 导入store
import store from '@/store'

import { Toast } from 'vant';

// 路由对象加全局前置守卫
// to：   去哪
// from:  从哪来
// next 是一个函数，调用它代表放行（跳转），不调用代表不放行（不跳转）
router.beforeEach((to, from, next) => {

  // 判断去的页面是不是需要登录的页面
  // 需要先给路由打上标签
  if (to.meta.needLogin) {
    // 证明是需要登录的页面 
    // 如何判断有没有登录？
    if (store.state.tokenObj.token) {

      next()
    } else {
      // 代表没登录，打回登录页
      // 页就是放行到登录页
      // 弹出一个轻提示
      Toast.fail('请先登录')
      // 除了打回登录页，还要记录一下原本想访问的页面是哪个路径
      // to就是我们原本想去的路由，因此打回登录页时，我们需要
      // 把原本要去的路由的路径记录下来,to.path就是原本想访问的路径
      // next的用法相当于是$router.push，所以也可以通过query传递参数
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }

  } else {

    next()
  }

})


// 官方提供的解决办法：
// 解决放行到别的页面会报错的提醒
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
